package com.smart.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.smart.common.PageInfo;
import com.smart.common.utils.AssertUtil;
import com.smart.model.domain.DictDO;
import com.smart.model.dtomapper.DictItemDtoMapper;
import com.smart.model.domain.DictItemDO;
import com.smart.mapper.DictItemMapper;
import com.smart.model.request.DictItemRequest;
import com.smart.service.DictItemService;
import com.smart.model.convert.DictItemConvert;
import com.smart.model.vo.DictItemVO;
import com.smart.service.DictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * @author zhanghong
 */
@Service
public class DictItemServiceImpl extends ServiceImpl<DictItemMapper, DictItemDO> implements DictItemService {
    @Autowired
    private DictItemMapper dictItemMapper;
    @Autowired
    private DictService dictService;

    @Override
    public DictItemVO getByKey(long id) {
        DictItemDO dictItemDO = getById(id);
        DictItemVO dictItemVO = DictItemDtoMapper.INSTANCE.do2VO(dictItemDO);
        return dictItemVO;
    }

    @Override
    public PageInfo<DictItemVO> pageQuery(DictItemRequest request) {
        long count = dictItemMapper.pageCount(request);
        List<DictItemDO> list = dictItemMapper.pageQuery(request, request.getPageSize(), request.fetchOffSet());
        List<DictItemVO> dictItemVOList = DictItemConvert.buildDictItemVoList(list);
        return new PageInfo(request.getPageNum(), request.getPageSize(), dictItemVOList, count);
    }

    @Override
    public List<DictItemVO> listQuery(DictItemRequest request) {
        List<DictItemDO> list = list();
        List<DictItemVO> dictItemVOS = DictItemConvert.buildDictItemVoList(list);
        return dictItemVOS;
    }

    @Override
    public Boolean add(DictItemRequest request) {
        DictItemDO dictItemDO = DictItemDtoMapper.INSTANCE.request2DO(request);
        save(dictItemDO);
        return true;
    }

    @Override
    public Boolean updateByKey(DictItemRequest request) {
        DictItemDO dictItemDO = DictItemDtoMapper.INSTANCE.request2DO(request);
        save(dictItemDO);
        return true;
    }

    @Override
    public List<DictItemVO> queryDictItemByDictCode(String dictCode) {
        DictDO dictDO = dictService.lambdaQuery().eq(DictDO::getDictCode, dictCode).one();
        AssertUtil.assertNotNull(dictDO, "非法的字典编码");

        List<DictItemDO> list = this.lambdaQuery().eq(DictItemDO::getDictId, dictDO.getId()).list();
        return Optional.ofNullable(list).map(DictItemConvert::buildDictItemVoList).orElse(Lists.newArrayList());
    }
}
